# -*- coding: utf-8 -*-
'''
Created on Aug 22, 2015

@author: Luo
'''

#encoding=utf-8
import sys, urllib, urllib2, json, socket
from urlparse import parse_qs, urlparse

appkey = '7e70b2733e1c74914ef84909bb679ce4' #APPKEY
mock = False

def search(keyword):
    url = 'http://api2.juheapi.com/mmb/search/simple' #request URL
    paramsData = {'keyword': keyword, 'key': appkey} #params
    params = urllib.urlencode(paramsData)
    
    if mock == True:
        content = '{"error_code":"200","reason":"请求成功","result":[{"siteName":"当当","spname":"佳能 Canon 700D EOS 700D  18-55mm STM 镜头 16G卡 摄影包 UV镜 礼包","sppic":"http://img32.ddimg.cn/35/35/1001863502-1_b_1.jpg","spprice":"3530","spurl":"http://www.manmanbuy.com/redirectUrl.aspx?bjid=737947\u0026u=黑夜"},{"siteName":"新蛋网","spname":"Canon 佳能 EOS 700D 单反相机 套机 - 含 EF-S 18-55mm f/3.5-5.6 IS STM 标准变焦镜头","sppic":"http://c3.neweggimages.com.cn/neweggpic2/neg/P180/A04-038-5GL-02.jpg","spprice":"3489.00","spurl":"http://www.manmanbuy.com/redirectUrl.aspx?bjid=11549715\u0026u=黑夜"},{"siteName":"苏宁易购","spname":"佳能(CANON) EOS 700D 单反套机 (EF-S 18-55MM F/3.5-5.6 IS STM 镜头)","sppic":"http://image2.suning.cn/b2c/catentries/000000000103798029_1_200x200.jpg","spprice":"3338.00","spurl":"http://www.manmanbuy.com/redirectUrl.aspx?bjid=11815675\u0026u=黑夜"},{"siteName":"亚马逊","spname":"Canon 佳能 EOS 700D 数码单反套机(EF-S 18-55mm f/3.5-5.6 IS STM 镜头)","sppic":"http://ec4.images-amazon.com/images/I/41KXMno9M7L._AA160_.jpg","spprice":"3583.00","spurl":"http://www.manmanbuy.com/redirectUrl.aspx?bjid=12182792\u0026u=黑夜"},{"siteName":"京东商城","spname":"佳能(Canon) EOS 700D 单反套机 (EF-S 18-55mm f/3.5-5.6 IS STM 镜头)","sppic":"http://img13.360buyimg.com/n7/g10/M00/12/12/rBEQWFFiTJUIAAAAAAG3hp5WHu0AADoSACOqwMAAbee163.jpg","spprice":"3799.00","spurl":"http://www.manmanbuy.com/redirectUrl.aspx?bjid=12202807\u0026u=黑夜"},{"siteName":"1号店","spname":"Canon 佳能 EOS 700D 单反套机 (EF-S 18-55mm f/3.5-5.6 IS STM 镜头)","sppic":"http://d7.yihaodianimg.com/N01/M02/50/9C/CgQCrVF46HyAVxkUAAGXbP8nbiw24201_200*200.jpg","spprice":"3599","spurl":"http://www.manmanbuy.com/redirectUrl.aspx?bjid=13496172\u0026u=黑夜"},{"siteName":"淘宝天猫","spname":"赠神器 佳能单反700D套机 EOS 700D 18-55 IS STM套机 正品行货","sppic":"//img.alicdn.com/bao/uploaded/i1/821711942/TB2eCWOXVXXXXbcXXXXXXXXXXXX_!!821711942.jpg_160x160.jpg","spprice":"3330.00","spurl":"http://www.manmanbuy.com/redirectUrl.aspx?bjid=27946203\u0026u=黑夜"},{"siteName":"国美在线","spname":"佳能(Canon)700D(18-55mm)单反单镜套装(官方标配)","sppic":"http://img2.gomein.net.cn/image/bbcimg/production_image/nimg/20130617/11/8001820383/103008705_160.jpg","spprice":"3320.00","spurl":"http://www.manmanbuy.com/redirectUrl.aspx?bjid=33129223\u0026u=黑夜"},{"siteName":"易迅网","spname":"佳能(Canon) EOS 700D 单反套机 (EF-S 18-55mm f/3.5-5.6 IS STM 镜头)","sppic":"http://img2.wgimg.com/qqbuy/2593170434/item-00000000000000000000006E9A90A402.0.jpg/200?55D6BB1C","spprice":"3499.00","spurl":"http://www.manmanbuy.com/redirectUrl.aspx?bjid=73223905\u0026u=黑夜"},{"siteName":"飞牛网","spname":"佳能（Canon） EOS 700D 单反套机 （EF-S 18-55mm f/3.5-5.6 IS STM 镜头）","sppic":"http://img01.fn-mart.com/C/item/2015/0126/201501C260000197/201501C260000107_939340596_200x200.jpg","spprice":"3888","spurl":"http://www.manmanbuy.com/redirectUrl.aspx?bjid=141083863\u0026u=黑夜"}]}'
    else:
        req = urllib2.Request(url, params)
        req.add_header('Content-Type', "application/x-www-form-urlencoded")
        resp = urllib2.urlopen(req, timeout=2)
        content = resp.read()
    if content:
        result = json.loads(content, 'utf-8')
        error_code = result['error_code']
        print error_code, result
        if(error_code == '200'):
            data = result['result'] #success data
            for d in data:
                params = parse_qs(urlparse(d["spurl"]).query, keep_blank_values=True)
                if d["sppic"] and d["sppic"].startswith("//"):
                    d["sppic"]  = "http:" + d["sppic"]
                d["id"] = params["bjid"][0]
            return data
        else:
            raise urllib2.HTTPError()
            #errorinfo = str(error_code)+":"+result['reason'] #false
            #return []
            
    return []
